<?php

declare(strict_types=1);

namespace App\Controller;

use App\Constants\WsCode;

use App\Controller\WsWorker\Close;
use App\Controller\WsWorker\Login;
use App\Task\GroupTask;
use Hyperf\Contract\OnCloseInterface;
use Hyperf\Contract\OnMessageInterface;
use Hyperf\Contract\OnOpenInterface;
use Hyperf\Memory\TableManager;
use Swoole\Http\Request;
use Swoole\Server;
use Swoole\Websocket\Frame;
use Hyperf\Utils\Codec\Json;
use Swoole\WebSocket\Server as WebSocketServer;

class WebSocketController extends AbstractController implements OnMessageInterface, OnOpenInterface, OnCloseInterface
{
    public function onMessage($server, Frame $frame): void
    {
        try {
            $data    = json::decode($frame->data);

            $method  = $data["method"];
            $class   = WsCode::ROUTE[$data["type"]];
            $results = $class::$method($frame->fd, $data);
            $results = json::encode($results);
            $server->push($frame->fd, $results);
        } catch (\Exception $e) {
           print_r($e);
        }

    }

    public function onClose($server, int $fd, int $reactorId): void
    {
        $class = WsCode::ROUTE["Close"];
        $class::close($fd);
    }

    public function onOpen($server, Request $request): void
    {
        $server->push($request->fd, 'open');
    }
}
